package com.sali.Tree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 JZ37 序列化二叉树
 */
public class JZ_37 {

    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        myXulie(root, sb);
        return sb.toString();
    }

    private void myXulie(TreeNode root, StringBuilder sb) {
        if ( root == null ) {
            sb.append("none,");
            return;
        }

        sb.append(root.val).append(",");

        myXulie(root.left, sb);
        myXulie(root.right, sb);

    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] strArr = data.split(",");
        List<String> strList = new ArrayList<>(Arrays.asList(strArr));
        return myFanxulie(strList);
    }

    private TreeNode myFanxulie(List<String> strList) {
        if ( strList.get(0).equals("none") ) {
            strList.remove(0);
            return null;
        }

        TreeNode curNode = new TreeNode(Integer.valueOf(strList.get(0)));
        strList.remove(0);
        curNode.left = myFanxulie(strList);
        curNode.right = myFanxulie(strList);
        return curNode;
    }

}
